package com.lqk.fnandroid

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import com.lqk.fbridge.FlutterBridgeActivity
import com.lqk.fnandroid.baen.User
import com.lqk.fnandroid.baen.str
import com.lqk.fnandroid.databinding.ActivityMainBinding
import com.lqk.fnandroid.livedata.LiveDataActivity
import com.lqk.fnandroid.navigation.NavigationActivity
import com.lqk.fnandroid.net.API
import com.lqk.fnandroid.net.OkHttpHelper
import com.lqk.fnandroid.net.RetrofitHelper
import com.lqk.fnandroid.room.RoomActivity
import com.lqk.fnandroid.viewmodel.ViewModelActivity
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.concurrent.thread

class MainActivity : FragmentActivity() {

    companion object {
        // Used to load the 'myapplication' library on application startup.
        init {
            System.loadLibrary("fnAndroid")
        }

        const val TAG = "MainActivity"
    }

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainLooper.queue.addIdleHandler {
            Log.d(TAG, "IdleHandler: 空闲")
            return@addIdleHandler false
        }

        // 添加 空白 Fragment
        if (supportFragmentManager.findFragmentByTag("com.lqk.jetpack.empty-fragment") == null) {
            supportFragmentManager
                .beginTransaction()
                .add(EmptyFragment(), "com.lqk.jetpack.empty-fragment")
                .commit()
            supportFragmentManager.executePendingTransactions()
        }

        lifecycle.addObserver(LifeCallback())

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Example of a call to a native method
        binding.sampleText.text = stringFromJNI()
        initListener()
        studyLiveData()
    }

    private fun studyLiveData() {
        LiveDataLocal.userInfo.observe(this) {
            Toast.makeText(this@MainActivity, it, Toast.LENGTH_SHORT).show()
        }
    }

    private fun initListener() {

        binding.sampleText.setOnClickListener {
            LiveDataLocal.userInfo.value = "修改内容: $it : ${binding.sampleText.text.toString()}"
            Log.d(TAG, "initListener: ${LiveDataLocal.userInfo}")
        }
        binding.btnStartFlutter.setOnClickListener {
            val flutterIntent = Intent(this@MainActivity, FlutterBridgeActivity::class.java)
            // 挂载引擎
            // 入口文件名称 没有 则 默认 lib/main.dart
            val fileName = binding.etDartFile.text.toString()
            if (fileName.isNotBlank()) {
                flutterIntent.putExtra(FlutterBridgeActivity.EXTRA_DART_FILE, fileName)
            }
            // 入口函数名称 默认 main 其他需要添加注释
            val funcName = binding.etFuncName.text.toString()
            if (funcName.isNotBlank()) {
                flutterIntent.putExtra(FlutterBridgeActivity.EXTRA_FUN_NAME, funcName)
            }
            // 根路由 同步到 window.defaultRouteName 的 内容
            val rootRoute = binding.etRootRoute.text.toString()
            if (rootRoute.isNotBlank()) {
                flutterIntent.putExtra(FlutterBridgeActivity.EXTRA_ROOT_ROUTE, rootRoute)
            }
            // 页面路由 默认 /
            val pageRoute = binding.etPageRoute.text.toString()
            if (pageRoute.isNotBlank()) {
                flutterIntent.putExtra(FlutterBridgeActivity.EXTRA_PAGE_ROUTE, pageRoute)
            }

            startActivity(flutterIntent)
        }
        binding.btnFlutter.setOnClickListener {
            startActivity(Intent(this@MainActivity, FlutterBridgeActivity::class.java))
        }
        binding.btnLiveData.setOnClickListener {
            LiveDataLocal.userInfo.value = "我要修改了"
            thread {
                Thread.sleep(2000)
                LiveDataLocal.userInfo.postValue("即将修改")
            }
            thread {
                Thread.sleep(4000)
                LiveDataLocal.userInfo.postValue("又即将修改")
            }
            startActivity(Intent(this@MainActivity, LiveDataActivity::class.java))
        }
        binding.btnViewModel.setOnClickListener {
            startActivity(Intent(this@MainActivity, ViewModelActivity::class.java))
        }
        binding.btnRoom.setOnClickListener {
            startActivity(Intent(this@MainActivity, RoomActivity::class.java))
        }
        binding.btnNavigation.setOnClickListener {
            startActivity(Intent(this@MainActivity, NavigationActivity::class.java))
        }

        binding.btnGet.setOnClickListener {
            Thread {
                val resp = OkHttpHelper.doGet("http://192.168.1.38:5001", hashMapOf())
                Log.d(TAG, "doGet: $resp")
            }.start()
        }
        binding.btnPost.setOnClickListener {
            Thread {
                val resp = OkHttpHelper.doPost("http://192.168.1.38:5001", hashMapOf())
                Log.d(TAG, "doPost: $resp")
            }.start()
        }
        binding.btnRetrofitGet.setOnClickListener {
            thread {
                val call = RetrofitHelper
                    .createService(API::class.java)
                    .helloGet()
                val resp = call.execute()
                Log.d(TAG, "get: ${resp.body()?.string()}")
            }
        }
        binding.btnRetrofitPost.setOnClickListener {
            thread {
                RetrofitHelper.createService(API::class.java)
                    .helloPost()
                    .enqueue(object : Callback<ResponseBody> {
                        override fun onResponse(
                            call: Call<ResponseBody>,
                            response: Response<ResponseBody>
                        ) {
                            Log.d(TAG, "onResponse: ${response.body()?.string()}")
                        }

                        override fun onFailure(call: Call<ResponseBody>, t: Throwable) {

                        }
                    })
            }
        }
        binding.btnRetrofitPostUser.setOnClickListener {
            thread {
                RetrofitHelper.createService(API::class.java)
                    .postUser(User("LQK", 28))
                    .enqueue(object : Callback<User> {
                        override fun onResponse(call: Call<User>, response: Response<User>) {
                            Log.d(TAG, "onResponse: ${response.body()?.str()}")
                        }

                        override fun onFailure(call: Call<User>, t: Throwable) {

                        }
                    })
            }
        }
    }

    /**
     * A native method that is implemented by the 'myapplication' native library,
     * which is packaged with this application.
     */
    external fun stringFromJNI(): String

}